var policyText = {
    "expiration": "2020-01-01T12:00:00.000Z", //设置该Policy的失效时间，超过这个失效时间之后，就没有办法通过这个policy上传文件了
    "conditions": [
    ["content-length-range", 0, 1048576000] // 设置上传文件的大小限制
    ]
};

accessid= 'TrJpgSnv7L5Qvovh';
accesskey= '7hRyK5CdOGyaaGhSmOAZGTLjhU4iDw';
host = 'http://skyedev.oss-cn-hangzhou.aliyuncs.com/';

var dateString=new Date().getTime();

var policyBase64 = Base64.encode(JSON.stringify(policyText))
message = policyBase64
var bytes = Crypto.HMAC(Crypto.SHA1, message, accesskey, { asBytes: true }) ;
var signature = Crypto.util.bytesToBase64(bytes);
var uploader = new plupload.Uploader({
	runtimes : 'html5,flash,silverlight,html4',
	browse_button : 'selectfiles', 
    //runtimes : 'flash',
	container: document.getElementById('container'),
	flash_swf_url : 'lib/plupload-2.1.2/js/Moxie.swf',
	silverlight_xap_url : 'lib/plupload-2.1.2/js/Moxie.xap',

    url : host,

	multipart_params: {
		'Filename': '${filename}', 
        'key' : 'rom/${filename}',
		'policy': policyBase64,
        'OSSAccessKeyId': accessid, 
        'success_action_status' : '200', //让服务端返回200,不然，默认会返回204
		'signature': signature,
	},

	init: {
		PostInit: function() {
			document.getElementById('ossfile').innerHTML = '';

			document.getElementById('postfiles').onclick = function() {
				//doNormalTest();
				uploader.start();
				return false;
			};
		},

		FilesAdded: function(up, files) {
			plupload.each(files, function(file) {
				document.getElementById('ossfile').innerHTML += '<div id="' + file.id + '">' + file.name+ ' (' + plupload.formatSize(file.size) + ')<b></b>'
				+'<div class="progress"><div class="progress-bar" style="width: 0%"></div></div>'
				+'</div>';
				doIncrementalTest(file);
				if(file.name.split('.')[1]=='ipa'){
					$('#inputIpaUrl').val("https://website-en.oss-us-west-1.aliyuncs.com/download/"+dateString+"/"+file.name);
				}
				
			});
		},

		UploadProgress: function(up, file) {
			var d = document.getElementById(file.id);
			d.getElementsByTagName('b')[0].innerHTML = '<span>' + file.percent + "%</span>";
            
            var prog = d.getElementsByTagName('div')[0];
			var progBar = prog.getElementsByTagName('div')[0]
			progBar.style.width= 2*file.percent+'px';
			progBar.setAttribute('aria-valuenow', file.percent);
		},

		FileUploaded: function(up, file, info) {
            //alert(info.status)
            if (info.status >= 200 || info.status < 200)
            {
        		$('#inputUrl').val("https://website-en.oss-us-west-1.aliyuncs.com/download/"+dateString+"/manifest.plist");
                document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = 'success';
            }
            else
            {
                document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = info.response;
            } 
		},

		Error: function(up, err) {
			document.getElementById('console').appendChild(document.createTextNode("\nError xml:" + err.response));
		}
	}
});

uploader.init();



var blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice,
log = document.getElementById('log'),

running = false,
ua = navigator.userAgent.toLowerCase();

function registerLog(str, className) {
    var elem = document.createElement('div');

    elem.innerHTML = str;
    elem.className = 'alert-message' + (className ? ' '  + className : '');
    log.appendChild(elem);
}

function doNormalTest(file) {
    if (running) {
        return;
    }
    //var input = document.getElementById(fileId);
    //if (!input.files.length) {
    //    registerLog('<strong>Please select a file.</strong><br/>');
    //    return;
    //}

    var fileReader = new FileReader(),
        //file = input.files[0],
        time;

    fileReader.onload = function (e) {
        running = false;

        if (file.size != e.target.result.byteLength) {
            registerLog('<strong>ERROR:</strong> Browser reported success but could not read the file until the end.<br/>', 'error');
        } else {
            registerLog('<strong>Finished loading!</strong><br/>', 'success');
            registerLog('<strong>Computed hash:</strong> ' + SparkMD5.ArrayBuffer.hash(e.target.result) + '<br/>', 'success'); // compute hash
            registerLog('<strong>Total time:</strong> ' + (new Date().getTime() - time) + 'ms<br/>', 'success');
        }
    };

    fileReader.onerror = function () {
        running = false;
        registerLog('<strong>ERROR:</strong> FileReader onerror was triggered, maybe the browser aborted due to high memory usage.<br/>', 'error');
    };

    running = true;
    registerLog('<strong>Starting normal test (' + file.name + ')</strong><br/>', 'info');
    console.dir(file);
    time = new Date().getTime();
    
    fileReader.readAsArrayBuffer(file);
}

function clearLog() {
    if (!running) {
        log.innerHTML = '';
    }
}

if (!('FileReader' in window) || !('File' in window) || !blobSlice) {
    registerLog('<p><strong>Your browser does not support the FileAPI or slicing of files.</strong></p>', 'error');
} else {
    registerLog('Keep your devtools closed otherwise this example will be a LOT slower', 'info');

    if (/chrome/.test(ua)) {
        if (location.protocol === 'file:') {
            registerLog('<p><strong>This example might not work in chrome because you are using the file:// protocol.</strong><br/>You can try to start chrome with -allow-file-access-from-files argument or spawn a local server instead. This is a security measure introduced in chrome, please <a target=\'_blank\' href=\'http://code.google.com/p/chromium/issues/detail?id=60889\'>see</a>.</p>');
        }
    }

    document.getElementById('normal').addEventListener('click', doNormalTest);
    document.getElementById('clear').addEventListener('click', clearLog);
}

function doIncrementalTest(file) {
    if (running) {
        return;
    }

    //if (!input.files.length) {
    //    registerLog('<strong>Please select a file.</strong><br/>');
    //    return;
    //}

    var blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice,
        //file = input.files[0],
        chunkSize = 2097152,                           // read in chunks of 2MB
        chunks = Math.ceil(file.size / chunkSize),
        currentChunk = 0,
        spark = new SparkMD5(),
        time,
        uniqueId = 'chunk_' + (new Date().getTime()),
        chunkId = null,
        fileReader = new FileReader();

    fileReader.onload = function (e) {
        if (currentChunk === 0) {
            registerLog('Read chunk number <strong id="' + uniqueId + '">' + (currentChunk + 1) + '</strong> of <strong>' + chunks + '</strong><br/>', 'info');
        } else {
            if (chunkId === null) {
                chunkId = document.getElementById(uniqueId);
            }

            chunkId.innerHTML = currentChunk + 1;
        }

        spark.appendBinary(e.target.result);                 // append array buffer
        currentChunk += 1;

        if (currentChunk < chunks) {
            loadNext();
        } else {
            running = false;
            registerLog('<strong>Finished loading!</strong><br/>', 'success');
            registerLog('<strong>Computed hash:</strong> ' + spark.end() + '<br/>', 'success'); // compute hash
            registerLog('<strong>Total time:</strong> ' + (new Date().getTime() - time) + 'ms<br/>', 'success');
        }
    };

    fileReader.onerror = function () {
        running = false;
        registerLog('<strong>Oops, something went wrong.</strong>', 'error');
    };

    function loadNext() {
        var start = currentChunk * chunkSize,
            end = start + chunkSize >= file.size ? file.size : start + chunkSize;

        fileReader.readAsBinaryString(blobSlice.call(file, start, end));
    }

    running = true;
    registerLog('<p></p><strong>Starting incremental test (' + file.name + ')</strong><br/>', 'info');
    time = new Date().getTime();
    loadNext();
}